using System;
using System.Collections.Generic;
using System.Text;
using MCromwell.StaffIntranet.Task.Tasks;
using MCromwell.StaffIntranet.Core;
using MCromwell.StaffIntranet.DependencyInjection;

namespace MCromwell.StaffIntranet.Presenters
{
    public class AuthenticationPresenter
    {
        private IAuthenticationTask task;
        private IAuthenticationView view;

        public AuthenticationPresenter(IAuthenticationView view)
            : this(IoC.Resolve<IAuthenticationTask>(), view)
        {
        }

        public AuthenticationPresenter(IAuthenticationTask task, IAuthenticationView view)
        {
            if (task == null)
                throw new ArgumentNullException("task", "task cannot be null");

            if (view == null)
                throw new ArgumentNullException("view", "view cannot be null");

            this.task = task;
            this.view = view;

            BindToViewEvents(view);
        }

        private void BindToViewEvents(IAuthenticationView view)
        {
            view.LoginPerformed += new LoginPerformedDelegate(HandleLoginEvent);
        }

        void HandleLoginEvent(object sender, LoginPerformedEventArgs e)
        {
            Guid authenticationToken = Guid.Empty;
            bool authenticatedCredentials = task.AuthenticateAgainst(new Credentials(e.Username, e.Password), out authenticationToken);
            if (authenticatedCredentials)
                view.CredentialsAuthenticated(authenticationToken);
            else
                view.DisplayError("cannot authenticate, either the username or password must be incorrect");
        }
                
    }
}
